package net.anzhuo.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.wanghaomiao.xpath.exception.XpathSyntaxErrorException;
import cn.wanghaomiao.xpath.model.JXDocument;
import cn.wanghaomiao.xpath.model.JXNode;
import net.anzhuo.entity.GsBase;
import net.anzhuo.entity.GsBranch;
import net.anzhuo.entity.GsChange;
import net.anzhuo.entity.GsGudong;
import net.anzhuo.entity.GsMember;
import net.anzhuo.entity.GsOuttouzi;

public class HttpClientUtils {
 public	GsBase gs=new GsBase();
 
 public List<GsGudong> gsGuDong=new ArrayList<GsGudong>();
 
 public List<GsOuttouzi> gsOutouzi=new ArrayList<GsOuttouzi>();
	
 public List<GsBranch>  gsBranch=new ArrayList<GsBranch> ();
 
 public List<GsMember>  gsMember=new ArrayList<GsMember> ();
 
 
 public List<GsChange>  gsChange=new ArrayList<GsChange>();
 
 
	public String getKeyNo(String name)
	{
		
		String result="";
		Document doc=Jsoup.parse(name);
		Element elem = doc.getElementById("searchlist");
		if(elem!=null)
		{
		 Elements	TableElem=elem.getElementsByClass("m_srchList");
		 if(TableElem!=null&&TableElem.size()>0)
		 {
			 Element table=TableElem.get(0);
			 Elements trlist=table.getElementsByTag("tr");
			 if(trlist!=null&&trlist.size()>0)
			 {
				Element tr1= trlist.get(1);
				
				Elements tds=tr1.getElementsByTag("td");
				
				if(tds!=null&&tds.size()>0)
				{
					Element td2=tds.get(1);
					
					Elements as=td2.getElementsByTag("a");
					
					if(as!=null&&as.size()>0)
					{
					  Element a=as.get(0);	  
					  result=a.attr("href");
					  result=result.replace("/firm_", "");
					  result=result.replace(".html","");
					}
				}
				
			 }
		 }
		}
		
		return result;
	}
	
	
	public boolean getBasicInfoData(String content,String name)
	{
		boolean result=false;
		
		JXDocument docNew=new JXDocument(content);
		
		try {
			List<Object> xpath_NameNode=docNew.sel("//div[@class='content']/div[@class='row title']/h1/allText()");
			//name
			if(xpath_NameNode!=null&&xpath_NameNode.size()==1)
			{
			gs.setName(xpath_NameNode.get(0).toString());
			}
						
		} catch (XpathSyntaxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//oldName
		try {
			List<Object> xpath_NameNode=docNew.sel("//div[@class='content']/div[@class='row tags']/span[2]/span");
			//name
			if(xpath_NameNode!=null&&xpath_NameNode.size()==1)
			{
			gs.setName2(((Element)xpath_NameNode.get(0)).attr("title"));
			}
						
		} catch (XpathSyntaxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//regAddress
		try {
			List<Object> xpath_NameNode=docNew.sel("//div[@class='content']/div[4]/span[3]/a[1]/allText()");
			//name
			if(xpath_NameNode!=null&&xpath_NameNode.size()==1)
			{
			gs.setRegAddress(xpath_NameNode.get(0).toString());
			}
						
		} catch (XpathSyntaxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("name="+gs.getName()+",regAddress="+gs.getRegAddress()+",oldName="+gs.getName2());
		
		
		return result;
	}
	
	public String getBasicInfo(String keyNo)
	{
		String result="";
		String url=null;
	
			
	

				url = "https://www.qichacha.com/firm_"+keyNo+".html";
			
		        String html = null;
		        for (int i = 1; i <= 3; i++) {
		            CloseableHttpClient httpclient = HttpClients.createDefault();// 创建httpClient对象
		            HttpGet httpget;
		            CloseableHttpResponse response = null;
		            httpget = new HttpGet(url);// 以get方式请求该URL
		           // HttpHost proxy = new HttpHost("221.7.255.167",8080);
		            RequestConfig requestConfig = RequestConfig.custom()
		                //    .setProxy(proxy)
		                    .setConnectTimeout(10000)
		                    .setSocketTimeout(10000)
		                    .setConnectionRequestTimeout(3000)
		                    .build();
		            httpget.setConfig(requestConfig);
		            httpget.addHeader(HttpHeaders.USER_AGENT,
		                    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
		          
		
		            try {
		                response = httpclient.execute(httpget);// 得到response对象
		                int resStatu = response.getStatusLine().getStatusCode();// 返回码
		                System.out.println("状态码" + resStatu);
		                if (resStatu == HttpStatus.SC_OK) {// 200正常 
		                    // 获得相应实体
		                    HttpEntity entity = response.getEntity();
		                
		                    if (entity != null) {
		                        html = EntityUtils.toString(entity);
		                        html = html.replace("&nbsp;", " ");
		                        break;
		                    }
		                }
		            } catch (Exception e) {
		                e.printStackTrace();
		            }
		            finally {
		                httpclient.getConnectionManager().shutdown();
		            }
		        }
		        return html;
	}
	
	public String getHtml(String name) {
	String url=null;
	try {
		url = "https://www.qichacha.com/search?key="+URLEncoder.encode(name, "utf-8");
	} catch (UnsupportedEncodingException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
        String html = null;
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpclient = HttpClients.createDefault();// 创建httpClient对象
            HttpGet httpget;
            CloseableHttpResponse response = null;
            httpget = new HttpGet(url);// 以get方式请求该URL
           // HttpHost proxy = new HttpHost("221.7.255.167",8080);
           
    
            httpget.addHeader(HttpHeaders.USER_AGENT,
                    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
            RequestConfig requestConfig = RequestConfig.custom()
                //    .setProxy(proxy)
                    .setConnectTimeout(10000)
                    .setSocketTimeout(10000)
                    .setConnectionRequestTimeout(3000)
                    .build();
            httpget.setConfig(requestConfig);
            try {
                response = httpclient.execute(httpget);// 得到response对象
                int resStatu = response.getStatusLine().getStatusCode();// 返回码
                System.out.println("状态码" + resStatu);
                if (resStatu == HttpStatus.SC_OK) {// 200正常 
                    // 获得相应实体
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8");
                        html = html.replace("&nbsp;", " ");
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                httpclient.getConnectionManager().shutdown();
            }
        }
        return html;
    }
	
	
	public static  void main(String[] args) throws IOException{
		HttpClientUtils js=new HttpClientUtils();
		
		String name="东方安卓(北京)征信有限公司";
		String content=js.getHtml(name);
		String keyNo=js.getKeyNo(content);
		System.out.println(keyNo);
		 content=js.getBasicInfo(keyNo);
		 //System.out.println(content);
		js.getBasicInfoData(content,name);
		}
	
	


}
